import { PlayerCoverBackMode } from "../home/control.js";
import { getAudioInfo, getAudioLyric } from "../service/ajax.js";
import { reactive } from "../util/reactive.js";
import { blur, formatLyricTime, formatSongLyric, formatSongTime } from "../util/util.js";

// 歌曲播放页面
export async function playerPage({ params: id = "" }) {
    // 更改歌曲是否返回推荐列表详情页还是去播放列表
    const lastRecommendId = window.localStorage.getItem("lastRecommendId");
    PlayerCoverBackMode("recommend", lastRecommendId);

    changePlayerMusicId(id);
}


const music = {
    data: [],
    lyric: [],
};
const musicDataProxy = reactive(
    {
        musicId: 1813926556,
    },
    initPlayer
)

export async function changePlayerMusicId(musicId) {
    const id = musicId;
    const musicData = await getAudioInfo(id);
    const musicLyric = await getAudioLyric(id);
    music.data = musicData;
    music.lyric = musicLyric;
    // 初始化播放器歌词
    music.lyric = formatSongLyric(musicLyric.lrc.lyric);
    musicDataProxy.musicId = id;
}

async function initPlayer() {
    let songInfo = music.data.songs[0];
    document.querySelector("#app").innerHTML = `
    <div class="player-background-image">
                <div class="player-content d-flex w">
                    <div class="player-album-cover d-flex">
                        <!-- 歌曲封面 -->
                         <div class="album">
                            <div class="cover running">
                                <img src="${songInfo.al.picUrl}" alt="">
                            </div>
                         </div>
                    </div>
                    <div class="player-lyric d-flex align-items-start">
                        <!-- 歌曲和歌词信息  -->
                         <h3 class="song-name">${songInfo.name}</h3>
                         <div class="song-info">
                            <span class="song-album">专辑：${songInfo.al.name}</span>
                            <span class="singer">歌手：${songInfo.ar[0].name}</span>
                            <span class="song-source">来源：${songInfo.al.name}</span>
                         </div>
                         <div class="lyric-wrap">
                            ${initLyric(music.lyric)}
                         </div>
                    </div>
                </div>
            </div>
    `;
    initPlayerEvent();
    imgBlur();
}
// 添加高斯模糊后的背景图
function imgBlur(){
    const imgBox=document.querySelector(".player-background-image");
    let imgSrc=music.data.songs[0].al.picUrl;
    blur(imgBox,imgSrc);
}

function initLyric(lyricData) {
    if (lyricData.length == 0) return "暂无歌词";
    let tempStr = "";
    lyricData.forEach((item) => {
        tempStr += `
        <p class="song-lyric-item" data-time='${item.time}'>${Object.keys(item).length > 0 ? item.lyric : ""}</p>
        `;
    });
    return tempStr;
}

// 歌词进度更新

function initPlayerEvent() {
    const audio = document.querySelector("#myAudio");
    
    const progressBar = document.querySelector(".progress-bar");// 获取进度条
    audio.addEventListener("timeupdate", (e) => {
        // 获取音乐播放当前的时间
        const lyricItem = document.querySelectorAll(".song-lyric-item");//获取所有歌词p标签对象
        if (!lyricItem.length || lyricItem.length == 1) return;
        const currentTime = e.target.currentTime;//获取当前播放时间
        let i = 0;
        Array.from(lyricItem).forEach((item) => {
            const time = item.getAttribute("data-time");
            if (currentTime > time) i++;
            item.classList.remove("active");//移除所有歌词的active类
        });
        if (i > 0) {
            lyricItem[i - 1].classList.add("active");//只有当i大于0时才添加当前歌词的active类
        }
        if (i > 5) {
            setScrollTop("lyric-wrap", "song-lyric-item", i - 1 - 5);
        }

        // 更新进度条    
        // const duration = audio.duration;// 获取音频的时长
        // const progress = currentTime / duration * 100;
        // progressBar.style.width = progress + "%";

        // 更新底部当前歌词时间
        // let cTime = formatLyricTime(currentTime);
        // document.querySelector(".current-time").innerText = cTime;

    })

    // 音乐暂停时让磁盘图片停止转动
    audio.addEventListener("ended", () => {
        // 歌曲播放完毕
        const albumCover=document.querySelector(".album .cover");
        if(!albumCover) return;
        albumCover.style.animationPlayState="paused";//暂停播放动画
    });
    audio.addEventListener("pause", () => {
        // 暂停播放
        const albumCover=document.querySelector(".album .cover");
        if(!albumCover) return;
        albumCover.style.animationPlayState="paused";//暂停播放动画
    });
    audio.addEventListener("playing", () => {
        // 播放
        const albumCover=document.querySelector(".album .cover");
        if(!albumCover) return;
        albumCover.style.animationPlayState="running";//播放动画
    });
        
}

// 滚动条自动滑动
// className：要滚动的容器的类名
// target：要滚动的目标，可以是数字，字符串，或者元素对象
// index：要滚动的目标在容器中的索引
function setScrollTop(className, target, index) {
    const ele = document.querySelector(`.${className}`);
    if (typeof target == "number") {
        ele.scrollTop = index * target;
    } else if (typeof target == "string") {
        const { height } = document.querySelector(`.${target}`).getBoundingClientRect();
        ele.scrollTop = index * height;
    } else if (target instanceof HTMLElement) {
        const { height } = target.getBoundingClientRect();
        ele.scrollTop = index * height;
    }
}


